package sy.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sy.dao.TsuggestionDaoI;
import sy.model.Tsuggestion;
import sy.pageModel.DataGrid;
import sy.pageModel.PageHelper;
import sy.service.SuggestionAdServiceI;
@Service
public class SuggestionAdServiceImpl implements SuggestionAdServiceI {
	@Autowired
	private TsuggestionDaoI tsuggestionDao;
	
	@Override
	public void delete(String id) {
		tsuggestionDao.delete(tsuggestionDao.get(Tsuggestion.class, id));
	}

	@Override
	public void add(Tsuggestion tsuggestion) throws Exception {
		Tsuggestion u = new Tsuggestion();
		u.setParm(tsuggestion.getParm());
		u.setSug(tsuggestion.getSug());
		u.setId(UUID.randomUUID().toString());
		//u.settime(new Date());
		tsuggestionDao.save(u);
	}
	
	private String orderHql(PageHelper ph) {
		String orderString = "";
		if (ph.getSort() != null && ph.getOrder() != null) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}
	@Override
	public DataGrid dataGrid(Tsuggestion tsuggestion, PageHelper ph) {
		DataGrid dg = new DataGrid();
		List<Tsuggestion> ul = new ArrayList<Tsuggestion>();
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Tsuggestion t ";
		List<Tsuggestion> l = tsuggestionDao.find(hql + whereHql(tsuggestion, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
		if (l != null && l.size() > 0) {
			for (Tsuggestion t : l) {
				Tsuggestion u = new Tsuggestion();
				BeanUtils.copyProperties(t, u);
				ul.add(u);
			}
		}
		dg.setRows(ul);
		dg.setTotal(tsuggestionDao.count("select count(*) " + hql + whereHql(tsuggestion, params), params));
		return dg;
	}
	private String whereHql(Tsuggestion tsuggestion, Map<String, Object> params) {
		String hql = "";
		if (tsuggestion != null) {
			hql += " where 1=1 ";
			if (tsuggestion.getParm() != null) {
				hql += " and t.parm like :parm";
				params.put("parm", "%%" + tsuggestion.getParm()+ "%%");
			}
			if (tsuggestion.getSug() != null) {
				hql += " and t.sug like :sug";
				params.put("sug", "%%" +tsuggestion.getSug() + "%%");
			}
		}
		return hql;
	}

	
}
